package cn.com.open.opensaas.scoreservice.service.impl;

import cn.com.open.opensaas.scoreservice.domain.OperateLogModel.OperateDescription;
import cn.com.open.opensaas.scoreservice.domain.OperateLogModel.OperateLog;
import cn.com.open.opensaas.scoreservice.mapper.OperateLogMapper;
import cn.com.open.opensaas.scoreservice.service.OperateLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service("operateLogService")
public class OperateLogServiceImpl implements OperateLogService {
	private static final Logger logger = LoggerFactory.getLogger(OperateLogServiceImpl.class);

	@Autowired
	private OperateLogMapper operateLogMapper;

	/**
	 * 保存日志.
	 *
	 * @param operateDescription 操作日志描述对象
	 * @param consumeTime        持续时间
	 */
	@Override
	public void saveLog(OperateDescription operateDescription, long consumeTime) {
		OperateLog operateLog = makeLog(operateDescription, consumeTime);
		savaLogModel(operateLog);
	}

	/**
	 * 日志保存.
	 *
	 * @param model 操作日志模型
	 * @return the boolean
	 */
	private void savaLogModel(OperateLog model) {
		try {
			operateLogMapper.insert(model);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}

	/**
	 * 创建操作日志类.
	 *
	 * @param operateDescription the operate description
	 * @param consumeTime        the consume time
	 * @return the operate log
	 */
	private OperateLog makeLog(OperateDescription operateDescription, long consumeTime) {
		//带有占位符的OptDescription
		String description = operateDescription.getDescription();
		if (description.length() > 0) {
			description = description + "|";
		}
		description += "Action监控：ControllerName：%s|ActionName:%s|总时间：%s ms|Action参数：%s|Http请求头:%s|客户端IP：%s|HttpMethod:%s";
		String duration = String.valueOf(consumeTime);
		//对应点位符填充值的数组
		String[] arr = {operateDescription.getControllerName(),
				operateDescription.getActionName(),
				duration,
				operateDescription.getActionParam(),
				operateDescription.getHttpHeader(),
				operateDescription.getCustomIp(),
				operateDescription.getMethod()};
		//对其进行填充
		String optDescription = String.format(description, arr);
		//打印输出OptDescription
		logger.info(optDescription);

		//创始OperateLog实体，调用数据库insert
		return new OperateLog(operateDescription.getOptUrl(),
				operateDescription.getControllerName(),
				operateDescription.getActionName(),
				operateDescription.getOptType(),
				new Date(),
				operateDescription.getCustomIp(),
				optDescription);
	}

}